package common;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.Iterator;
import java.io.IOException;

public class ItemsTag extends BodyTagSupport {
  private Iterator iterator = null;
  private Object item = null;

  public int doStartTag() throws JspTagException {
    
    	PartTag partTag = (PartTag) findAncestorWithClass(this, PartTag.class);
    	if (partTag == null) {
      		throw new JspTagException("ItemsTag: items tag not inside parttag tag");
   	 }
   	 iterator = partTag.getIterator();
   	 if (iterator == null || !iterator.hasNext()) return(SKIP_BODY);
   	 item = iterator.next();
    	 return(EVAL_BODY_TAG);
  }

  // process the body again with the next item if it exists
  public int doAfterBody() {
    if (iterator.hasNext()) {
      item = iterator.next();
      return(EVAL_BODY_TAG);
    } else return(SKIP_BODY);
  }

  // print out the resulting body content to the JSP page and evaluate the
  // rest of the page
  public int doEndTag() {
    try {
      BodyContent body = getBodyContent();
      if (body != null) {
        JspWriter out = body.getEnclosingWriter();
        out.print(body.getString());
      }
    } catch(IOException ioe) {
      System.out.println("Error handling items tag: " + ioe);
    }
    return(EVAL_PAGE);
  }

  // getter for inner tags
  public Object getCurrentItem() {
    return item;
  }
}

